import numpy as np
import pandas as pd
from pandas import DataFrame
from statsmodels.tsa.arima.model import ARIMA
import matplotlib.pyplot as plt
import statsmodels.api as sm  # acf,pacf图
from scipy import stats
from statsmodels.graphics.api import qqplot
import scipy.stats as sct

import seaborn as sns

from statsmodels.tsa.seasonal import seasonal_decompose


# 按间距中的绿色按钮以运行脚本。
if __name__ == '__main__':
    filename = 'bitcoin'
    data = pd.read_excel("data/" + filename + ".xlsx")
    print(data)

    # decomposition = seasonal_decompose(data, filt=7)
    # trend = decomposition.trend  # 趋势部分
    # seasonal = decomposition.seasonal  # 季节性部分
    # residual = decomposition.resid  # 残留部分
    # decomposition.plot()
    # plt.show()

    # 定阶,d=1
    # tmp = []
    # aic_matric = []
    # for p in range(10):
    #     temp = []
    #     for q in range(10):
    #         try:
    #             # mid = 1
    #             mid = ARIMA(data, order=(p, 1, q)).fit().aic
    #             tmp.append([mid, p, q])
    #             temp.append(mid)
    #         except:
    #             tmp.append([None, p, q])
    #             temp.append(temp[q-1])
    #     # print(temp)
    #     aic_matric.append(temp)
    # print(aic_matric)
    # sns.heatmap(aic_matric, cmap="YlGnBu")
    # plt.savefig('save/' + filename + '/aic_heatmap.png', bbox_inches='tight')
    # tmp = pd.DataFrame(tmp, columns=['aic', 'p', 'q'])
    # print(tmp[tmp['aic'] == tmp['aic'].min()])
    # p = tmp[tmp['aic'] == tmp['aic'].min()]['p']
    # q = tmp[tmp['aic'] == tmp['aic'].min()]['q']
    # 定阶结果 p=8,q=7,bitcoin
    # 定阶结果 p=5,q=8,gold

    model = ARIMA(data, order=(8, 1, 7)).fit()
    predict_ts = model.predict(start=-365, end=-1)
    plt.figure(figsize=(10, 6))
    plt.plot(predict_ts, label="forecast")
    plt.plot(data[-365:-1], label="real")
    plt.xlabel('Date', fontsize=12, verticalalignment='top')
    plt.ylabel('Prices', fontsize=14, horizontalalignment='center')
    plt.legend()
    plt.savefig('save/' + filename + '/predictions.png', bbox_inches='tight')
    # plt.show()

    predict_ts = model.predict(start=-215, end=-150)
    plt.figure(figsize=(10, 6))
    plt.plot(predict_ts, label="forecast")
    plt.plot(data[-215:-150], label="real")
    plt.xlabel('Date', fontsize=12, verticalalignment='top')
    plt.ylabel('Prices', fontsize=14, horizontalalignment='center')
    plt.legend()
    plt.savefig('save/' + filename + '/part_predictions.png', bbox_inches='tight')
    # plt.show()

    print(model.summary())


    # plot residual errors
    residuals = DataFrame(model.resid)
    residuals[1:].plot()
    plt.savefig('save/' + filename + '/residuals.png', bbox_inches='tight')
    plt.show()

    # # residuals.plot(kind='kde')
    # # # plt.show()
    # # print(residuals.describe())
    # #
    # # # ACF、PCF图
    # # fig = sm.graphics.tsa.plot_acf(residuals)
    # # plt.show()
    # # fig = sm.graphics.tsa.plot_pacf(residuals)
    # # plt.show()
    # #
    # # # QQ图观察是否符合正态分布
    # # print(stats.normaltest(residuals))
    # # fig = plt.figure(figsize=(24, 16))
    # # ax = fig.add_subplot(111)
    # # fig = qqplot(model.resid, line='q', ax=ax, fit=True)
    # # plt.show()
    # #
    # ks test
    print(np.std(residuals))
    #
    # 保存残差
    residuals.to_excel('save/' + filename + '/'+filename+'_residuals.xlsx')
